package com.dayu.finecomm.protocol.codec;

import java.util.Arrays;

import com.dayu.finecomm.utils.Helpers;

import io.netty.buffer.ByteBuf;

/**
 * @ClassName: FixedMagicFrameDecoder
 * @Description:特定帧节的解码器，例如RPS8000：
 * @author: 戴卫国
 * @date: 2018年2月23日 下午4:30:06
 * 
 * @param <T>
 * @Copyright: 2018 dayu Inc. All rights reserved.
 */
public abstract class FixedMagicFrameDecoder<T> extends ProtocolDecoder<T> {

	public final byte[] startMagic;
	public final byte[] endMagic;
	public final int minLength;
	public final boolean longest;

	public FixedMagicFrameDecoder(byte[] startMagic, byte[] endMagic, int minLength, boolean longest) {

		this.startMagic = startMagic;
		this.endMagic = endMagic;

		this.minLength = minLength;
		this.longest = longest;
	}

	public FixedMagicFrameDecoder(byte[] startMagic, byte[] endMagic, int minLength) {

		this(startMagic, endMagic, minLength, false);
	}

	public FixedMagicFrameDecoder(String startMagic, String endMagic, int minLength) {

		this(startMagic.getBytes(Helpers.ASCII), endMagic.getBytes(Helpers.ASCII), minLength);
	}

	@Override
	public int check(ByteBuf in) {

		if (in.readableBytes() < minLength && in.readableBytes() < startMagic.length)
			return -1;

		ByteBuf b1 = in.readBytes(startMagic.length);

		if (!Arrays.equals(b1.array(), startMagic)) {
			return -1;
		}

		if (minLength - startMagic.length > 0) {
			if (in.readableBytes() >= minLength - startMagic.length) {
				in.skipBytes(minLength - startMagic.length);
			} else {
				return -1;
			}

		}

		int mark = -1;

		while (in.readableBytes() >= endMagic.length) {

			b1 = in.slice(in.readerIndex(), endMagic.length).readBytes(endMagic.length);

			if (Arrays.equals(b1.array(), endMagic)) {

				mark = in.readerIndex() + endMagic.length;

				if (!this.longest)
					return mark;
			}

			in.skipBytes(1);
		}

		return mark;
	}
}
